import React from 'react'
import { BaseListPage, columnRenders, http, IBaseListPageState, IBaseListPageProps, UdModal, UdModalForm, IUdFormItem, UdTable, UdDateRangePicker, uaaApp } from '@/lib'
import { Button, Select, InputNumber, Input, Spin, Upload, message } from 'antd'
import apis from '@/apis/AboutQuota'
import comApis from '@/apis'
import dayjs from 'dayjs'
import udMainStore from '@/store/UdMain'
import UdSelect from '@/components/UdFormControls/UdSelect'
import './style.scss'
import YearQuotaModalContent, { EditYearQuotaModalContent } from './component/YearQuotaModalContent'
import { downBlobFile } from '@/utils/methods'

const { Option } = Select
const importBtnAuthor = 'quota_employee_manager_quotaYearLimitImport'
const exportBtnAuthor = 'quota_employee_manager_quotaYearLimitexport'
const updateBtnAuthor = 'quota_employee_manager_saveOrUpdateYearLimit'

class List extends BaseListPage<ICustomerYearQuotaListProps, ICustomerYearQuotaListState> {
  protected useConditionsField = true
// 隐藏掉头曲二曲
public hideArr: any = ['头曲','二曲','泸州老窖头曲酒类销售有限公司','泸州老窖二曲酒类销售有限公司']
public brandList = udMainStore.brandList.filter(item => this.hideArr.indexOf(item.title) === -1)
  private modal
  constructor(props) {
    super(props)
    this.state = {
      title: '客户年度总配额控制',
      queryApi: apis.CustomerYearQuotaList,
      rowKey: 'id',
      conditions: [
        { label: '品牌公司', id: 'brandCode', render: <UdSelect options={this.brandList} /> },
        {
          label: '考核年度', id: 'year', render: () => <UdSelect options={this.state.assessYearList} showSearch={true} optionFilterProp='children' />
        },
        { label: '客户名称', id: 'dealerName' },
        { label: '客户编码', id: 'dealerCode' },
        { label: '物料分类名称', id: 'productGroupName' },
        { label: '物料分类编码', id: 'productGroupCode' },
      ],
      columns: [
        { title: '客户编码', dataIndex: 'dealerCode', minWidth: '100px' },
        { title: '客户名称', dataIndex: 'dealerName', width: '10%', minWidth: '140px' },
        { title: '客户类型', dataIndex: 'dealerType', fixedWidth: '70px' },
        { title: '物料分类编号', dataIndex: 'productGroupCode', fixedWidth: '80px' },
        { title: '物料分类名称', dataIndex: 'productGroupName', width: '10%', minWidth: '120px' },
        { title: '考核年度', dataIndex: 'year', fixedWidth: '50px' },
        { title: '全年总配额数量/件', dataIndex: 'number', fixedWidth: '100px' },
        {
          title: '起止时间', dataIndex: 'startTime', fixedWidth: '140px', render: (text, record) => {
            const endTime = record.endTime
            let render = text ? dayjs(text).format('YYYY-MM-DD') : ''
            render += endTime ? '~' + dayjs(endTime).format('YYYY-MM-DD') : ''
            return render
          }
        },
        { title: '创建人', dataIndex: 'createName', fixedWidth: '60px' },
        { title: '创建时间', dataIndex: 'createTime', fixedWidth: '120px' },
        {
          title: '操作', dataIndex: 'operate', fixedWidth: '40px', fixed: 'right', render: columnRenders.operate([
            { title: '编辑', auth: updateBtnAuthor, action: (text, record) => this.editHandle(record) }
          ])
        },
      ],
      leftBtns: [
        uaaApp.canUse(updateBtnAuthor) && <Button onClick={this.addHandle} type='primary'>新增</Button>,
        uaaApp.canUse(importBtnAuthor) && <Button type='primary' onClick={this.importModal}>导入</Button>,
        uaaApp.canUse(exportBtnAuthor) && (() => <Button disabled={!this.existSelectedRow()} onClick={this.exportHandle}>导出</Button>),
      ],
      tableProps: {
        scroll: { x: true },
      },
      assessYearList: [],
      uploading: false,
      downloading: false,
    }
  }

  componentDidMount() {
    super.componentDidMount()
    this.getAssessYearList()
  }

  render() {
    const loadingTips = this.state.uploading ? '正在上传，请稍后...' : '正在下载，请稍后...'
    return (
      <Spin spinning={this.state.uploading || this.state.downloading} tip={loadingTips}>
        {super.render()}
      </Spin>
    )
  }

  public getAssessYearList = () => {
    http.get(comApis.GetQuotaAssessYearList).then(res => {
      const assessYearList = res.data?.map(({ year: value, name: title }) => ({ value, title })) || []
      this.setState({
        assessYearList,
      })
    })
  }

  public addHandle = () => {
    UdModal.open({
      title: '新增年度总配额设置',
      className: 'customer-year-quota-modal',
      width: 900,
      content: <YearQuotaModalContent />,
      onOk: (values) => {
        const { dealerName, brandCode, ...params } = values
        if (dealerName) {
          params.dealerName = dealerName.label
        }
        if (brandCode) {
          params.brandCode = brandCode.key
          params.brandName = brandCode.label
        }
        // 检查物料行是否存在没有填写配额数量
        const tableHasBlank = params.saveQuotaYearLimitMaterialClassifyList.some(item => !item.number && item.number !== 0)
        if (tableHasBlank) {
          message.error('总配额数量不能为空')
          return Promise.reject()
        }
        return http.post(apis.UpdateCustomerYearQuota, params).then(res => {
          message.success('新增成功')
          this.query()
        })
      }
    })
  }

  public editHandle = (row) => {
    UdModal.open({
      title: '修改年度总配额设置',
      className: 'customer-year-quota-modal',
      width: 740,
      content: <EditYearQuotaModalContent values={row} />,
      onOk: (values) => {
        delete row.productGroupCode
        delete row.productGroupName
        delete row.number
        // 修改传primaryId（控制表主表主键id），列表id（物料明细主键ID）唯一，primaryId不唯一
        let params = { id: row.primaryId, ...values }
        // 检查物料行是否存在没有填写配额数量
        const tableHasBlank = params.saveQuotaYearLimitMaterialClassifyList.some(item => !item.number && item.number !== 0)
        if (tableHasBlank) {
          message.error('总配额数量不能为空')
          return Promise.reject()
        }
        return http.post(apis.UpdateCustomerYearQuota, params).then(res => {
          message.success('修改成功')
          this.query()
        })
      }
    })
  }

  private importModal = () => {
    this.modal = UdModal.open({
      title: '导入年度总配额',
      width: 300,
      content: <>
        <div className='import-file-modal'>
          <Button type='primary' onClick={this.downloadTpl}>下载模板</Button>
          <Upload showUploadList={false} customRequest={this.importUser}><Button type='primary'>导入</Button></Upload>
        </div>
      </>,
      footer: null,
      maskClosable: false,
      centered: true,
    })
  }

  private importUser = (option) => {
    this.modal && this.modal.destroy()
    this.setState({ uploading: true })
    const { file } = option
    const formData = new FormData()
    formData.append('file', file)
    http.post(apis.ImportYearQuota, formData).then(res => {
      message.success('上传成功')
      this.query()
    }).finally(() => this.setState({ uploading: false }))
  }

  private downloadTpl = () => {
    http.post(apis.DownloadTpl, {}, { responseType: 'arraybuffer' }).then(res => {
      if (!res.data.code) {
        downBlobFile(res.data, '客户年度总配额导入模板')
      }
    })
  }

  public exportHandle = () => {
    this.setState({ downloading: true })
    const params = this.state.selectedRows
    http.post(apis.ExportYearQuota, params, { responseType: 'arraybuffer' }).then(res => {
      if (!res.data.code) {
        downBlobFile(res.data, '客户年度总配')
        const  { tableProps } = this.state
        // 置空选中的数据
        tableProps.rowSelection.selectedRowKeys = []
        this.setState({
          selectedRowKeys: [],
          selectedRows: [],
          tableProps,
        })
      }
    }).finally(() => {
      this.setState({ downloading: false })
    })
  }

}

export default List

interface ICustomerYearQuotaListState extends IBaseListPageState {
  assessYearList: any[]
  uploading: boolean
  downloading: boolean
}

interface ICustomerYearQuotaListProps extends IBaseListPageProps {

}

